// 配置管理组合式函数

import { ref } from 'vue'
import type { PanelConfig, TradingState, MarketData } from '@/types/trading'
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
import { emit, listen } from '@tauri-apps/api/event'
import { UserStorageService } from '../../services/userStorage'

export function useConfigManager() {
  const activeSet = ref(1)

  // 从面板ID中提取合约代码的辅助函数
  const getContractCodeFromPanelId = (panelId: string): string | null => {
    // 尝试从合约存储中获取面板对应的合约信息
    try {
      // 从localStorage中获取面板合约映射信息
      const panelContractsData = localStorage.getItem('panel_contracts')
      if (panelContractsData) {
        const panelContracts = JSON.parse(panelContractsData)
        return panelContracts[panelId]?.code || null
      }
      return null
    } catch (error) {
      return null
    }
  }

  // 从交易面板获取实际配置数据
  const getPanelConfiguration = async (panelId: string, panel: WebviewWindow): Promise<any> => {
    return new Promise((resolve, reject) => {
      let isResolved = false
      let unlistenFn: (() => void) | null = null
      
      const timeout = setTimeout(() => {
        if (!isResolved) {
          isResolved = true
          if (unlistenFn) {
            unlistenFn()
          }
          reject(new Error(`获取面板${panelId}配置超时`))
        }
      }, 5000) // 5秒超时

      // 监听面板配置响应
      listen(`panel-config-response-${panelId}`, (event) => {
        if (!isResolved) {
          isResolved = true
          clearTimeout(timeout)
          if (unlistenFn) {
            unlistenFn()
          }
          resolve(event.payload)
        }
      }).then(fn => {
        unlistenFn = fn
      }).catch(error => {
        if (!isResolved) {
          isResolved = true
          clearTimeout(timeout)
          reject(error)
        }
      })

      // 向面板发送获取配置请求
      emit(`get-panel-config-${panelId}`, { requestId: panelId })
        .catch(error => {
          if (!isResolved) {
            isResolved = true
            clearTimeout(timeout)
            if (unlistenFn) {
              unlistenFn()
            }
            reject(error)
          }
        })
    })
  }

  // 保存配置到XML
  const saveConfiguration = async (tradingPanels: Map<string, WebviewWindow>) => {
    try {
      // 收集所有面板的窗口信息和状态
      const panelConfigs: PanelConfig[] = []

      for (const [panelId, panel] of Array.from(tradingPanels.entries())) {
        if (panel) {
          try {
            // 解析面板ID获取集合编号
            const setNumber = parseInt(panelId.split('-')[2])

            // 获取面板的合约代码
            const contractCode = getContractCodeFromPanelId(panelId)
            const panelTitle = contractCode || `交易面板 - 集合${setNumber}`

            // 获取面板的实际配置数据（包含窗口信息）
            let tradingState: TradingState, marketData: MarketData, windowInfo: any, priceTick: number = 1
            try {
              const panelConfig = await getPanelConfiguration(panelId, panel)
              tradingState = panelConfig.tradingState
              marketData = panelConfig.marketData
              windowInfo = panelConfig.window // 从面板获取的窗口信息
              priceTick = panelConfig.priceTick || 1 // 获取价格间距，默认为1
            } catch (error) {
              // 使用默认值作为后备
              tradingState = {
                currentPrice: 0,
                fontSize: 11,
                cellHeight: 18,
                orderType: 'A',
                lightOrderQuantity: 1,
                heavyOrderQuantity: 2,
                positionMode: 'open',
                cancelMode: 'limited',
                maxCancelOrders: 489,
                currentCancelCount: 0
              }
              marketData = {
                totalVolume: 0,
                totalPosition: 0,
                dailyPositionChange: 0,
                priceChangePercent: 0
              }
            }

            // 获取完整的显示器信息
            const monitorInfo = await getMonitorInfo(windowInfo.x, windowInfo.y)

            // 计算基于显示器的相对坐标
            const relativeX = windowInfo.x - monitorInfo.position.x
            const relativeY = windowInfo.y - monitorInfo.position.y
            

            // 面板配置 - 使用相对坐标
            const panelConfig: PanelConfig = {
              id: panelId,
              setNumber: setNumber,
              title: panelTitle,
              window: {
                ...windowInfo,
                x: relativeX, // 保存相对于显示器的X坐标
                y: relativeY  // 保存相对于显示器的Y坐标
              },
              tradingState: tradingState,
              marketData: marketData,
              priceTick: priceTick,
              screenNumber: monitorInfo.screenNumber,
              monitorId: monitorInfo.monitorId,
              monitorName: monitorInfo.monitorName,
              monitorPosition: monitorInfo.position,
              monitorSize: monitorInfo.size,
              timestamp: new Date().toISOString()
            }

            panelConfigs.push(panelConfig)
          } catch (error) {
          }
        }
      }

      // 生成XML内容
      const xmlContent = await generateTradingPanelXML(panelConfigs)

      // 保存到文件
      await saveTradingPanelXML(xmlContent)

      // 同时保存到localStorage作为备份
      const config = {
        activeSet: activeSet.value,
        panelConfigs: panelConfigs,
        timestamp: new Date().toISOString()
      }
      localStorage.setItem('trading_controller_config', JSON.stringify(config))

    } catch (error) {
    }
  }

  // 生成交易面板XML内容 - 按照用户指定的格式
  const generateTradingPanelXML = async (panelConfigs: PanelConfig[]) => {
    // 获取用户账号信息
    const userInfo = UserStorageService.getUserInfo()
    const accountNumber = userInfo?.account || '93015007' // 默认账号

    let xml = `<?xml version="1.0" encoding="UTF-8"?>
<a>`

    // 使用 for...of 循环来支持异步操作
    for (const config of panelConfigs) {
      // 从面板配置中获取合约代码
      const contractCode = getContractCodeFromPanelId(config.id) || config.title.replace('交易面板 - 集合', 'contract')

      // 计算金手指值 (FZ) - 根据交易状态中的选项计算
      const fzValue = calculateFingerValue(config.tradingState)

      // 获取轻仓重仓数量
      const lightQuantity = config.tradingState.lightOrderQuantity || 1
      const heavyQuantity = config.tradingState.heavyOrderQuantity || 5

      // 判断多模式还是单模式 (MS) - 根据订单类型判断
      const modeValue = config.tradingState.orderType === 'A' ? 'A' : 'B'

      // 使用保存的显示器信息，如果没有则重新计算
      const screenNumber = config.screenNumber || await calculateScreenNumber(config.window.x, config.window.y)
      const monitorId = config.monitorId || ''
      const monitorName = config.monitorName || ''

      // a标签
      // accountNumber 账户信息
      // title: 合约代码
      // X: 窗口X坐标
      // Y: 窗口Y坐标
      // Width: 窗口宽度
      // Height: 窗口高度
      // RowHeight: 行高
      // FZ: 金手指值
      // Z_NUM: 轻仓数量
      // Y_NUM: 重仓数量
      // MS: 轻重仓类型
      // SC: 屏幕编号
      // PID: 面板ID
      // PT: 价格跳动间距
      // MonitorId: 监视器ID
      // MonitorName: 监视器名称
      xml += `
    <a${accountNumber} Title="${contractCode}" X="${config.window.x}" Y="${config.window.y}" Width="${config.window.width}" Height="${config.window.height}" RowHeight="${config.tradingState.cellHeight || 16}" FZ="${fzValue}" Z_NUM="${lightQuantity}" Y_NUM="${heavyQuantity}" MS="${modeValue}" SC="${screenNumber}" PID="${config.id}" PT="${config.priceTick || 1}" MonitorId="${monitorId}" MonitorName="${monitorName}" />`
    }

    xml += `
</a>`

    return xml
  }



  // 计算金手指值的辅助函数
  const calculateFingerValue = (_tradingState: TradingState): number => {
    // 根据交易状态中的选项计算金手指值
    // 这里可以根据具体的业务逻辑来计算
    // 暂时返回一个默认值，可以根据实际需求调整
    return 1 // 默认金手指值
  }

  // 获取显示器信息和标识的辅助函数
  const getMonitorInfo = async (x: number, y: number): Promise<{
    screenNumber: number;
    monitorId: string;
    monitorName: string;
    position: { x: number; y: number };
    size: { width: number; height: number };
  }> => {
    try {
      // 使用Tauri API获取所有监视器信息
      const { availableMonitors, monitorFromPoint } = await import('@tauri-apps/api/window')

      // 获取所有监视器列表
      const monitors = await availableMonitors()

      // 尝试根据窗口位置找到对应的监视器
      const monitor = await monitorFromPoint(x, y)
      if (monitor) {

        // 找到当前监视器在列表中的索引
        const screenIndex = monitors.findIndex(m =>
          m.position.x === monitor.position.x &&
          m.position.y === monitor.position.y &&
          m.size.width === monitor.size.width &&
          m.size.height === monitor.size.height
        )

        if (screenIndex >= 0) {
          const targetMonitor = monitors[screenIndex]
          // 生成唯一的显示器标识，使用位置和尺寸信息
          const monitorId = `${targetMonitor.position.x}_${targetMonitor.position.y}_${targetMonitor.size.width}_${targetMonitor.size.height}`

          return {
            screenNumber: screenIndex + 1, // 屏幕编号从1开始
            monitorId: monitorId,
            monitorName: targetMonitor.name || `显示器${screenIndex + 1}`,
            position: targetMonitor.position,
            size: targetMonitor.size
          }
        }
      }

      // 如果无法确定，使用第一个显示器作为默认值
      const primaryMonitor = monitors[0] || {
        position: { x: 0, y: 0 },
        size: { width: 1920, height: 1080 },
        name: '主显示器'
      }

      const monitorId = `${primaryMonitor.position.x}_${primaryMonitor.position.y}_${primaryMonitor.size.width}_${primaryMonitor.size.height}`

      return {
        screenNumber: 1,
        monitorId: monitorId,
        monitorName: primaryMonitor.name || '主显示器',
        position: primaryMonitor.position,
        size: primaryMonitor.size
      }
    } catch (error) {
      // 返回默认值
      return {
        screenNumber: 1,
        monitorId: '0_0_1920_1080',
        monitorName: '默认显示器',
        position: { x: 0, y: 0 },
        size: { width: 1920, height: 1080 }
      }
    }
  }

  // 计算屏幕编号的辅助函数（保持向后兼容）
  const calculateScreenNumber = async (x: number, y: number): Promise<number> => {
    const monitorInfo = await getMonitorInfo(x, y)
    return monitorInfo.screenNumber
  }



  // 保存XML到config文件夹
  const saveTradingPanelXML = async (xmlContent: string) => {
    try {
      const { invoke } = await import('@tauri-apps/api/core')

      // 生成默认文件名
      const fileName = `td_config.xml`

      // 保存到config文件夹
      const savedPath = await invoke('save_config_file', {
        filename: fileName,
        content: xmlContent
      })

      return savedPath
    } catch (error) {
      throw error
    }
  }

  // 加载配置
  const loadConfiguration = () => {
    try {
      const saved = localStorage.getItem('trading_controller_config')
      if (saved) {
        const config = JSON.parse(saved)
        activeSet.value = config.activeSet || 1
      }
    } catch (error) {
    }
  }

  return {
    activeSet,
    saveConfiguration,
    loadConfiguration
  }
}
